<template>
  <div class="avatar-uploader">
    <!--
      action 必传的属性 提供一个后端接口地址, 如果你不希望提供一个固定的后端地址
        此时可以给action ''或者'#'

        auto-upload 是否在选取文件后立即进行上传
        默认为true    立即进行上传
        不希望进行上传  ->false
    -->
    <el-upload

      action="#"
      list-type="picture-card"
      :http-request="handleUpload"
      :file-list="fileList"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-change="handleChange"
      :limit="limit"
      :class="{disabled:isDisabled}"
      :before-upload="handleBeforeUpload"
    >
      <span>上传图片</span>
      <i class="el-icon-circle-close" />
    </el-upload>
    <el-dialog title="预览" :visible="isShow" @close="isShow=false">
    <div style="text-align: center">
    <img :src="imgUrl" alt="" style="width;:100% ">
    </div>

    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 导入腾讯云的包(sdk)

const cos = new COS({
  SecretId: 'AKIDgCTVIq9C0YqtgEWZNvEI6ex0oMfiV2JO', // 身份识别ID
  SecretKey: 'tZ0C9qIUQ7ZlhOp0wc2D8nDNIxNXYP3S' // 身份秘钥
})
export default {
  name: 'ImageUpload',
  props: {
    limit: {
      type: Number,
      default: 1
    },

    // 数据回显的父传子过来的地址
    img: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imgUrl: '',
      isShow: false,
      fileList: [
        // {
        //   name: 'food.jpeg',
        //   url: 'https://img2.baidu.com/it/u=4244269751,4000533845&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
        // },
        // {
        //   name: 'food2.jpeg',
        //   url: 'https://img0.baidu.com/it/u=2783255881,2944448631&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500'
        // },
        // {
        //   name: 'food3.jpeg',
        //   url: 'https://img1.baidu.com/it/u=1016138010,1907110459&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'
        // }
      ]
    }
  },

  // 数据回显时--监听img的变化:如果有变化,就添加到fileList数组
  watch: {
    img (newValue) {
      if (newValue) {
        // this.fileList.push({
        //   url: this.img
        // })
        // 优化:
        this.fileList = [{ url: this.img }]
      } else {
        this.fileList = []
      }
    }
  },
  computed: {
    isDisabled () {
      return this.fileList.length >= this.limit
    },
    isAllUploadSuccess () {
      return this.fileList.every(item => item.status === 'success')
    }
  },
  methods: {
    // 校验
    handleBeforeUpload (file) {
      // file => 添加的文件对象
      // console.log(file)
      // this.$message.error('你错了!')
      // return false

      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }

      return true
    },

    // 预览
    handlePreview (file) {
      this.isShow = true
      console.log(file)
      this.imgUrl = file.url
    },
    // 删除
    handleRemove (file, fileList) {
      this.fileList = [...fileList]
    },
    // 上传
    handleUpload (obj) {
      // URL.createObjectURL() 本地预览 blob
      // console.log('去上传吧')

      const uid = obj.file.uid
      const fileObj = this.fileList.find(item => item.uid === uid)
      fileObj.status = 'uploading'
      cos.putObject({
        Bucket: 'hrsass-99-1312445828', /* 填入自己的存储桶，必须字段 */
        Region: 'ap-shanghai', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: 'hrsass-99-' + parseInt(Math.random() * 99999) + obj.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD', // 设置对象存储类型: 标准
        Body: obj.file, // 上传的文件对象
        onProgress: (progressData) => {
          // console.log(JSON.stringify(progressData))
          // this.percent = parseInt(progressData.percent * 100)
          fileObj.percentage = parseInt(progressData.percent * 100)
        }
      }, (err, data) => {
        // 注意使用箭头函数,避免this问题(this => 组件)
        // 成功或者失败走这里
        // console.log(this)
        // console.log(err || data)
        if (err) return console.log('上传失败', err)

        // 更新数据!
        fileObj.url = 'https://' + data.Location
        // console.log(data.Location)
        // 要把生成的线上地址传出去给父组件使用!!!!
        // this.$emit('changeImg', data.Location)
        // 注意:之前传递过去的地址不全,没有带https://---所以要传递完全的线上地址,如下!!!
        this.$emit('changeImg', fileObj.url)
        setTimeout(() => {
          fileObj.status = 'success'
        }, 1000)
      })
    },
    // 同步
    handleChange (file, fileList) {
      this.fileList = [...fileList]
      // console.log(file)
    }
  }
}
</script>
<style lang="scss" scoped>
.disabled {

  ::v-deep {
    .el-upload--picture-card {
      display: none;
    }
  }
}
.avatar-uploader {
    display: inline-block;
    vertical-align: middle;
    line-height: 1;
    margin-left: 4px;
    i{
      position: absolute;
    right: 0;
    top: 0;
    transform: translate(50%,-50%);
    background: #fff;
    font-size: 18px;
    color: #999;
    }
::v-deep {.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width: 100px;
    height: 60px;
    line-height: 60px;
  }
  .el-upload-list__item{
     width: 100px;
    height: 60px;
    border: 0;
    margin: 0;
  }
}
  el-upload {
    display: inline-block;
    text-align: center;
    cursor: pointer;
    outline: 0;
}
}
</style>
